package DAO;

import beans.Logs;
import dbutils.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class LogDaoImpl implements LogDao{
    //顾客
    @Override
    public List<Logs> queryLog(int userId) {
        if (userId == 0){
            return null;
        }
        Connection conn = DBHelper.getConn();
        String sql = "select * from Logs WHERE customer = '" + userId + "'; ";
        PreparedStatement stat = null;
        ResultSet rs = null;
        List<Logs> logslist = new ArrayList<>();
        try {
            stat = conn.prepareStatement(sql);
            rs = stat.executeQuery();//executeQuery 该方法用来执行查询语句
            while (rs.next()){
                Logs log = new Logs();
                log.setUserName(rs.getString("userName"));
                log.setTimes(rs.getString("times"));
                log.setLogContext(rs.getString("LogContext"));
                logslist.add(log);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBHelper.closeAll(conn,stat,rs);
        }
        if (logslist.isEmpty()){
            return null;
        }else {
            return logslist;
        }
    }

    @Override
    public void addLog(Logs log) {
        Connection conn = DBHelper.getConn();
        String sql = "INSERT Logs (userName,times,logContext) VALUE(?,?,?);";
        PreparedStatement stat = null;
        ResultSet rs = null;
        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1,log.getUserName());
            stat.setString(2,log.getTimes());
            stat.setString(3,log.getLogContext());
            stat.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            DBHelper.closeAll(conn,stat,rs);
        }
    }
}
